package com.loyal.qr.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.BeepManager;
import com.google.zxing.client.android.Intents;
import com.loyal.qr.R;
import com.loyal.qr.zxing.BarcodeCallback;
import com.loyal.qr.zxing.BarcodeResult;
import com.loyal.qr.zxing.DecoratedBarcodeView;
import com.loyal.qr.zxing.DefaultDecoderFactory;

import java.util.List;

public class PortActivity extends AppCompatActivity {
    private DecoratedBarcodeView barcodeView;
    private BeepManager beepManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_port);
        Toolbar toolbar = findViewById(R.id.toolbar);
        String title = getIntent().getStringExtra("title");
        toolbar.setTitle(TextUtils.isEmpty(title) ? "扫一扫" : title);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        barcodeView = findViewById(R.id.decoratedBarcodeView);

        barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory());
        barcodeView.decodeContinuous(callback);
        beepManager = new BeepManager(this);
    }

    private final BarcodeCallback callback = new BarcodeCallback() {
        @Override
        public void barcodeResult(BarcodeResult barcodeResult) {
            beepManager.playBeepSoundAndVibrate();
            String result = barcodeResult.getText();
            Intent intent = new Intent(getIntent());
            intent.putExtra(Intents.Scan.RESULT, result);
            setResult(RESULT_OK, intent);
            finish();
        }

        @Override
        public void possibleResultPoints(List<ResultPoint> resultPoints) {
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (null != barcodeView)
            barcodeView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != barcodeView)
            barcodeView.pause();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return null != barcodeView && barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }
}
